// pages/order_list/index.js
import {
    getOrderList
} from "../../api/order.js"
import {
    getNavigationbar,
} from "../../api/index.js"
import {
    ReDistributionMall,
    ReMallPay
} from "../../api/shipping.js"
import {
    ReMallShopping
} from "../../api/index.js"
Page({
    options: {
        styleIsolation: "shared"
    },
    /**
     * 
     * 页面的初始数据
     */
    data: {
        active: 0,
        showMian: false,
        orderListMian: false,
        tabList: [{
            name: '全部'
        }, {
            name: '待付款'
        }, {
            name: '待发货'
        }, {
            name: '待收货'
        }, {
            name: '已完成'
        }],
        scrollViewHeight: 0, // 当前页面可滚动区域
        orderList: [],
        hanShow: false,
        out_trade_no: '',
        numberstO:false,
        currentPage: 1, // 当前页码
    },

    /**
     * 供应商选中回调函数方法
     * @param {*} e 
     */
    supCheckSelChange(event) {
        console.log('111', event.currentTarget.dataset)
        const id = event.currentTarget.dataset.value; // 获取当前选中状态
        const check = event.currentTarget.dataset.type; // 获取当前数据项
        console.log('点', id, check)
        if (check) {
            console.log('进==')
            // 取消选中逻辑
            this.data.orderList.forEach(element => {
                if (element.id == id) {
                    element.check = false
                }
            });
        } else {
            // 选中逻辑
            this.data.orderList.forEach(element => {
                if (parseInt(element.id) == parseInt(id)) {
                    console.log('123156')
                    element.check = true
                }
            });
        }
        console.log('结构', this.data.orderList)
        this.setData({
            orderList: this.data.orderList
        })
    },
    onClickLeft() {
        const pages = getCurrentPages();
        if (pages.length > 1) {
            wx.navigateBack();
        } else {
            wx.reLaunch({
                url: '/pages/index/index'
            });
        }
    },
    brandCheckSelChange(e) {
        console.log('e', e)
    },
    payTip() {
        let list = [];
        this.data.orderList.forEach(element => {
            if (element.check === true) {
                console.log('123156');
                list.push(element.id);
            }
        });

        let idString = list.join(',');
        console.log(idString);
        getNavigationbar({
            act: 'multi_repay',
            orderids: idString,

        }).then(resj => { 
            let  openids = wx.getStorageSync('OPENID') 
            console.log('支付', resj)
            if (resj.result == 101) {
                wx.showModal({
                    title: '',
                    content: resj.msg,
                    showCancel: false, // 是否显示取消按钮，设为false表示不显示
                    confirmText: '确定', // 确定按钮的文本
                    success(res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                        }
                    }
                });
            } else {
                let that = this;
                this.data.out_trade_no = resj.out_trade_no
                let token = wx.getStorageSync('TOKEN')
                console.log('支付', resj)
                ReMallPay({
                    act: "mini_wechat_commit",
                    appid: 'wx11508f3ee9dd6329',
                    openid: openids,
                    channel: "",
                    "out_trade_no": resj.out_trade_no
                }).then(res => {
                    console.log('微信支付', res,'token',token)
                    // 在需要显示带有确定按钮的模态框的地方调用该方法
                    if (res.result == 101) {
                        wx.showModal({
                            title: '',
                            content: res.msg,
                            showCancel: false, // 是否显示取消按钮，设为false表示不显示
                            confirmText: '确定', // 确定按钮的文本
                            success(res) {
                                if (res.confirm) {
                                    console.log('用户点击确定');
                                }
                            }
                        });
                    } else {
                        if (res.channel == 'mini_wechat') {
                            // 跳转到汇付小程序进行支付操作
                            wx.navigateToMiniProgram({
                                appId: res.appid,
                                envVersion: 'trial',
                                path: res.path + '?out_trade_no=' + resj.out_trade_no + '&token=' + token + '&type=mini_program',
                                success(res) {
                                    setTimeout(() => {
                                        that.checkPaymentStatus()
                                    }, 1000);
                                    // 支付完成后返回的回调函数
                                    wx.redirectTo({
                                        url: '/pages/order_list/index',
                                    })
                                },
                                fail(res) {
                                    console.log('res123', )
                                  
                                    setTimeout(() => {
                                        that.checkPaymentStatus()
                                    }, 1000);
                                }
                            });
                        } else {
                            wx.requestPayment({
                                provider: "wxpay",
                                appid: "wx11508f3ee9dd6329",
                                timeStamp: res.timestamp,
                                nonceStr: res.noncestr,
                                package: res.package,
                                partnerid: res.partnerid,
                                signType: res.sign_type,
                                paySign: res.sign,
                                success: function (res) {
                                    // 支付成功的回调
                                    console.log('支付成功的回调', res)
    
                                    this.getOrderList();
                                },
                                fail: function (res) {
                                    // 支付失败的回调
    
                                    wx.showToast({
                                        title: '取消支付',
                                        icon: 'none',
                                        duration: 2000
                                    });
    
    
                                    console.log('支付失败的回调', res)
                                }
                            });
                        }
    
                    }
    
    
                })
            }
        })

    },

    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        wx.getSystemInfo({
            success: function (res) {
                const windowHeight = res.windowHeight + 70;
                console.log('手机屏幕高度：', windowHeight);

                // 进行适配操作，例如设置元素高度为屏幕高度的一半
                const halfScreenHeight = windowHeight / 2;
                console.log('屏幕高度的一半：', halfScreenHeight);
                that.setData({
                    scrollViewHeight: windowHeight - 70
                })
            }
        });
    },

    /**
     * 获取订单列表回调函数方法
     */
    getOrderList(currentPage) {
        console.log('currentPage', currentPage)
        this.data.currentPage = currentPage || 1;
        console.log('this.data.active', this.data.active);
        wx.setStorageSync('currentPage',  this.data.currentPage);
        const getOrderListByType = (type) => {
            getOrderList({
                act: 'orderlist',
                type: type,
                p: this.data.currentPage,
            }).then(res => {
                res.forEach(element => {
                    const statuStr = getStatusString(element);
                    const num = +element.numbers;
                    Object.assign(element, {
                        statuStr: statuStr,
                        data: num,
                        check: false
                    });
                });
                const newOrderList = this.data.currentPage === 1 ? res : this.data.orderList.concat(res);
                if (this.data.orderList.length > 1) {
                    this.data.hanShow = true
                }
                this.setData({
                    orderList: newOrderList,
                    showMian: true,
                    hanShow: this.data.hanShow,
                    orderListMian: true
                });
                console.log('获取订单列表回调函数方法', res, 'newOrderList', newOrderList);
            });
        };

        const getStatusString = (element) => {
            let statuStr = "";

            if (element.order_type == 5) {
                statuStr = element.isrefund == 1 ? "集采失败，已退款" : "集采失败，退款失败";
            } else if (element.isrefund == 2) {
                statuStr = "交易关闭";
            } else {
                switch (parseInt(element.status)) {
                    case 0:
                    case 4:
                        statuStr = element.ispay == 1 ? "已付款" : (element.paytype == 9 ? "线下支付，未发货" : "未付款");
                        if (element.ispay == 1 && element.order_type == 5) {
                            statuStr = element.pintuan_state == 1 ? "集采成功，待发货" : (element.pintuan_state == 0 ? "已付款，待成团" : "集采失败");
                        }
                        break;
                    case 1:
                    case 2:
                    case 3:
                        statuStr = "已发货";
                        break;
                    case 5:
                        statuStr = element.flag == 0 ? "交易成功" : (element.flag == 1 ? "交易成功|待确认入库" : "交易成功|入库完成");
                        break;
                    case 8:
                        statuStr = "已结算";
                        break;
                    case 9:
                    case 10:
                        statuStr = "交易关闭";
                        break;
                    case 11:
                        if (element.recieve_days ?? 0 <= 7) {
                            statuStr = element.flag == 0 ? "交易成功" : (element.flag == 1 ? "交易成功|待确认入库" : "交易成功|入库完成");
                        } else {
                            statuStr = element.flag == 0 ? "交易完成" : (element.flag == 1 ? "交易完成|待确认入库" : "交易完成|入库完成");
                        }
                        break;
                    default:
                        console.log('执行结束');
                        statuStr = "";
                }
            }

            return statuStr;
        };

        switch (this.data.active) {
            case 0:
                getOrderListByType('all');
                break;
            case 1:
                getOrderListByType('0');
                break;
            case 2:
                getOrderListByType('7');
                break;
            case 3:
                getOrderListByType('8');
                break;
            case 4:
                getOrderListByType('9');
                break;
            default:

                console.log('未知active值');
        }
    },
    // 检测订单支付状态的函数
    checkPaymentStatus() {
        if (this.data.out_trade_no != '') {
            ReMallShopping({
                act: 'check_order_state',
                out_trade_no: this.data.out_trade_no,

            }).then(res => {
                if (res.ispay == 1) {
                    wx.reLaunch({
                        url: '/pages/order_list/index',
                    })
                } else {
                    // wx.showModal({
                    //     title: '',
                    //     content: '订单未支付',
                    //     showCancel: false, // 是否显示取消按钮，设为false表示不显示
                    //     confirmText: '确定', // 确定按钮的文本
                    //     success(res) {
                    //         if (res.confirm) {
                    //             wx.redirectTo({
                    //                 url: '/pages/order_list/index',
                    //             })
                    //         }
                    //     }
                    // });
                }
                console.log('检测订单支付状态的函数', res)
            })
        }
    },
    /**
     * 跳转
     * @param {*} event 
     */
    enter(event) {
        console.log('e', event)
        let obj = {
            ...event.currentTarget.dataset.value,
            agent_name: event.currentTarget.dataset.value.agent_name
        }
        let objStr = encodeURIComponent(JSON.stringify(obj));
        wx.navigateTo({
            url: '/pages/brand_detail/index?obj=' + objStr,
        })
    },
    /**
     * 支付继续付款
     */
    payment(val) {
        let  openids = wx.getStorageSync('OPENID') 
        console.log('支付', val,openids)
        getNavigationbar({
            act: 'repay',
            id: val.target.dataset.value,

        }).then(resj => {
            if (resj.result == 101) {
                wx.showModal({
                    title: '提示',
                    content: res.msg,
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            wx.navigateBack()
                        }
                    }
                })
                return
            }
            let that = this;
            this.data.out_trade_no = resj.out_trade_no
            let token = wx.getStorageSync('TOKEN')
            console.log('支付', resj)
            ReMallPay({
                act: "mini_wechat_commit",
                appid: 'wx11508f3ee9dd6329',
                openid: openids,
                channel: "",
                "out_trade_no": resj.out_trade_no
            }).then(res => {
                console.log('微信支付', res,'token',token)
                // 在需要显示带有确定按钮的模态框的地方调用该方法
                if (res.result == 101) {
                    wx.showModal({
                        title: '',
                        content: res.msg,
                        showCancel: false, // 是否显示取消按钮，设为false表示不显示
                        confirmText: '确定', // 确定按钮的文本
                        success(res) {
                            if (res.confirm) {
                                console.log('用户点击确定');
                            }
                        }
                    });
                } else {
                    if (res.channel == 'mini_wechat') {
                        // 跳转到汇付小程序进行支付操作
                        wx.navigateToMiniProgram({
                            appId: res.appid,
                            envVersion: 'trial',
                            path: res.path + '?out_trade_no=' + resj.out_trade_no + '&token=' + token + '&type=mini_program',
                            success(res) {
                                wx.redirectTo({
                                    url: '/pages/order_list/index',
                                })
                                // 支付完成后返回的回调函数

                            },
                            fail(res) {
                                console.log('res123', )
                                setTimeout(() => {
                                    that.checkPaymentStatus()
                                }, 1000);
                                // 跳转失败的处理逻辑
                             
                            }
                        });
                    } else {
                        wx.requestPayment({
                            provider: "wxpay",
                            appid: "wx11508f3ee9dd6329",
                            timeStamp: res.timestamp,
                            nonceStr: res.noncestr,
                            package: res.package,
                            partnerid: res.partnerid,
                            signType: res.sign_type,
                            paySign: res.sign,
                            success: function (res) {
                                // 支付成功的回调
                                console.log('支付成功的回调', res)

                                this.getOrderList();
                            },
                            fail: function (res) {
                                // 支付失败的回调

                                wx.showToast({
                                    title: '取消支付',
                                    icon: 'none',
                                    duration: 2000
                                });


                                console.log('支付失败的回调', res)
                            }
                        });
                    }

                }


            })

        });
    },
    // 再次购买
    Purchase(e) {
        console.log('e', e)

        if (e.target.dataset.type != '6') {
            getNavigationbar({
                act: 'order_rebuy',
                orderid: e.currentTarget.dataset.value.id,
    
            }).then(resj => { 
                wx.reLaunch({
                    url: '/pages/goods_cart/index',
                })
            })
        } else {
            ReDistributionMall({
                act: 'order_rebuy',
                orderid: e.currentTarget.dataset.value.id,
    
            }).then(resj => { 
                wx.navigateTo({
                    url: `/pages/behalf-shopping-cart/index`
                })
            })
        }

        
       
     
    },
    // 取消订单
    cancellationOrder(val) {
        console.log('点击',val)
        let that = this;
        wx.showModal({
            title: '订单取消',
            content: '取消后无法恢复',
            showCancel: true, // 是否显示取消按钮，设为true表示显示
            confirmText: '确定取消', // 确定按钮的文本
            cancelText: '暂不取消', // 取消按钮的文本
            confirmColor: '#ff0000', // 确定按钮的颜色
            cancelColor: '#999999', // 取消按钮的颜色
            contentColor: '#000000', // content文本颜色
            success(res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                    getNavigationbar({
                        act: 'cancelOrder',
                        id: val.currentTarget.dataset.value.id,
                        agentid: val.currentTarget.dataset.value.agentid,
                    }).then(res => {
                        if (res.result == 101) {
                            return wx.showModal({
                                title: '',
                                content: res.msg,
                                showCancel: false, // 是否显示取消按钮，设为false表示不显示
                                confirmText: '确定', // 确定按钮的文本
                                success(res) {
                                    if (res.confirm) {
                                        console.log('用户点击确定');
                                    }
                                }
                            });
                        } else {
                           
                            getApp().Tips({
                                title: "取消成功"
                            })
                            setTimeout(()=>{
                                that.getOrderList();
                            },500)
                        }
                        console.log('取消后无法恢复', res)
                      
                    });
                } else if (res.cancel) {
                    console.log('用户点击取消');

                }
            }
        });
    },
    // 查看物流
    getViewlogistic(val) {
        console.log('e', val)

        getNavigationbar({
            act: 'getlogistics',
            "is_multiterm": 1,
            orderid: val.target.dataset.value.id || ''
        }).then(res => {
            console.log('查看物流', res)
            if (res.result == 84115) {
                wx.nextTick(() => {
                    wx.showModal({
                        title: '',
                        content: res.msg,
                        showCancel: false, // 是否显示取消按钮，设为false表示不显示
                        confirmText: '确定', // 确定按钮的文本
                        success(res) {
                            if (res.confirm) {

                                console.log('用户点击确定');
                            }
                        }
                    });
                })
            } else {
                if(res.length > 1) {
                    wx.navigateTo({
                        url: '/subpackages/pages/sub1/index?data=' + JSON.stringify(val.target.dataset.value.id)
                    });
                } else {
                    wx.navigateTo({
                        url: '/subpackages/pages/Orderlogistics/index?data=' + JSON.stringify(res),
                      })
                }
              
            }
        })
    },
    // 一件入库
    Oneclickstorage(val) {
        console.log('val', val)
        wx.navigateTo({
            url: '/pages/select_product/index?data=' + JSON.stringify(val.target.dataset.value),
        })
    },
    // 确认收货
    Confirmreceipt(val) {
        console.log('e', val)
        let that = this
        wx.showModal({
            title: '提示',
            content: '确认收货',
            showCancel: true, // 是否显示取消按钮，设为false表示不显示
            confirmText: '确定', // 确定按钮的文本
            cancelText: "取消",
            success(res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                    getNavigationbar({
                        act: 'confirm_receipt',
                        agentid: val.target.dataset.value.agentid || '',
                        orderid: val.target.dataset.value.id || ''
                    }).then(res => {
                        console.log('确认收货', res)
                        if (res.result == 84115) {
                            return wx.nextTick(() => {
                                getApp().Tips({
                                    title:res.msg
                                })
                            })
                        } 
                        if (res.result == 101) {
                            // return
                            wx.nextTick(() => {
                                getApp().Tips({
                                    title:res.msg
                                })
                            })
                        }
                        wx.nextTick(() => {
                             
                              that.getOrderList();
                        })
                        getApp().Tips({
                            title: "确认成功"
                        })
                    })
                }
            }
        });

    },
    // 联系客服
    freeTell() {
        wx.makePhoneCall({
            phoneNumber: "18377766475", //仅为示例，并非真实的电话号码
            success: function () {
                console.log("拨打电话成功！");
            },
            fail: function () {
                console.log("拨打电话失败！");
            },
        });
    },
    handleScrollToLower() {
        console.log('触发到底部提示打印');

        let data = {

            currentPage: this.data.currentPage + 1,
            counts: 10,
        }
        this.setData({
            currentPage: this.data.currentPage + 1,
            loading: true
        });
        this.getOrderList(this.data.currentPage);

    },
    /**
     * 切换标签页回调函数方法
     * @param {*} e 
     */
    handleTabsChange(e) {
        this.setData({
            active: e.detail.index
        })
        this.getOrderList()
    },

    /**
     * 查看订单详情回调函数方法
     */
    handleViewOrderDetail(val) {
        console.log('val', val)
        if (val.currentTarget.dataset != '') {
            wx.navigateTo({
                url: `/pages/order_detail/index?data=${JSON.stringify(val)}`,
            })
            this.setData({
                numberstO:true
            })
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.data.active = 0
        this.data.currentPage = 1
        wx.setStorageSync('currentPage',  this.data.currentPage);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.computeScrollViewHeight()
        
       
        if(wx.getStorageSync('currentPage') <= 1) {
            this.getOrderList()
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        try {
            if(this.data.numberstO == false) {
                wx.setStorageSync('currentPage',  1);
            }
          
        } catch(e){
            //错误
        }
         
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})